//
//  StorageCommentViewController.m
//  danpin
//
//  Created by chuangjia on 17/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "StorageCommentViewController.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "RackCommentCell.h"
#import "HcCustomKeyboard.h"
#import "ZToastManager.h"
#import "BaseModel.h"
#import "WTStatusBar.h"
#import "OtherUserCenterVC.h"

@interface StorageCommentViewController ()<UITableViewDataSource,UITableViewDelegate,HcCustomKeyboardDelegate,UIActionSheetDelegate>
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,strong) HcCustomKeyboard *keyBordView;
@property(nonatomic,assign)int  commentType;
@property(nonatomic,strong)NSDictionary*  commentDictionary;
@end

@implementation StorageCommentViewController
@synthesize commentId=_commentId;
@synthesize commentType=_commentType;
@synthesize commentDictionary=_commentDictionary;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.navTitle = @"全部评论";
    self.isIndex = NO;
    self.isLoadFinished =NO;
    self.isRequesting =NO;
    self.isRefresh=NO;
    self.currentPage=0;
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
    [self initUI];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc
{
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView=nil;
    [self.dataArray removeAllObjects];
    self.dataArray=nil;
    [HcCustomKeyboard customKeyboard].mDelegate=nil;
    [[HcCustomKeyboard customKeyboard].mTextView removeFromSuperview];
    [HcCustomKeyboard customKeyboard].mTextView=nil;
    [[HcCustomKeyboard customKeyboard].mTextView resignFirstResponder];
    self.keyBordView=nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.frame.size.width, self.view.frame.size.height-hightAuto(65)-40) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor = [UIColor whiteColor];
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.separatorStyle= UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tbView];
    __weak typeof (self) wSelf = self;
    self.currentPage = 0;
    [_tbView addPullToRefreshWithActionHandler:^{
        wSelf.isRequesting = YES;
        wSelf.isRefresh = NO;
        wSelf.currentPage = 0;
        wSelf.isLoadFinished = NO;
        [wSelf.tbView.pullToRefreshView startAnimating];
        [wSelf getCommentListData];
    }];
    //
    //
    [_tbView.pullToRefreshView setOYStyle];
    
    [_tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        
        if (wSelf.isLoadFinished) {
            return;
        }
        
        wSelf.isRefresh = NO;
        if ([wSelf.dataArray count]>0) {
            wSelf.currentPage =(int)[wSelf.dataArray count];
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        [wSelf getCommentListData];
    }];
    
    //
    [[HcCustomKeyboard customKeyboard] textViewShowView:self customKeyboardDelegate:self];

}
#pragma mark---
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>_dataArray.count) {
        return 0;
    }
    NSDictionary *data =[_dataArray objectAtIndex:indexPath.row];
    return [RackCommentCell returnCellHeight:data];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RackCommentCell *cell = (RackCommentCell*)[tableView  dequeueReusableCellWithIdentifier:@"RackCommentCell"];
    if(cell == nil)
    {
        cell = [[RackCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    if (indexPath.row>=[_dataArray count]) {
        return cell;
    }
    NSDictionary *data =[_dataArray objectAtIndex:indexPath.row];
    [cell showInfo:data key:@"RackCommentCell" indexPath:indexPath];
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}
-(void)getCommentListData
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    [dict setValue:self.commentId forKey:@"photo_id"];
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    [BaseModel commentList:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    } failure:^(NSError *error) {
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    }];
    
}
-(void)parserResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        
        id dataarray =[resultObject objectForKey:@"data"];
        if (dataarray && [dataarray isKindOfClass:[NSArray class]]) {
            if (self.currentPage == 0 && [dataarray count]>0) {
                [_dataArray removeAllObjects];
            }
            for (id di in dataarray) {
                if (di && [di isKindOfClass:[NSDictionary class]])
                {
                    [_dataArray addObject:di];
                }
            }
        }
        
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        if (self.isLoadFinished)
        {
            
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
    }
    
    [self.tbView reloadData];
    self.isRequesting = NO;
    
}
//
-(void)talkBtnClick:(UITextView *)textViewGet
{
    if(textViewGet.text.length==0)
    {
        [[ZToastManager ShardInstance] showtoast:@"请输入内容"];
        return;
    }
    if (_commentType==1)
    { //回复
        NSString *comment_id =[[NSString stringWithFormat:@"%@",[_commentDictionary objectForKey:@"comment_id"]] replaceNullString];
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        [dict setValue:@"comment" forKey:@"action"];
        [dict setValue:comment_id forKey:@"comment_id"];
        [dict setValue:@"" forKey:@"good_id"];
        [dict setValue:self.commentId forKey:@"photo_id"];
        [dict setValue:textViewGet.text forKey:@"text"];
        
        __weak typeof (self) wSelf = self;
        [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
            if (result==nil) {
                return ;
            }
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *resultt = (NSDictionary*)result;
                NSString *msg = [resultt stringForKey:@"msg"];
                if (msg.length>0) {
                    [[ZToastManager ShardInstance] showtoast:msg];
                }
                id comments =[resultt objectForKey:@"comments"];
                if (comments && [comments isKindOfClass:[NSArray class]]) {
                    for (id cmt in comments) {
                        if (cmt && [cmt isKindOfClass:[NSDictionary class]]) {
                            [_dataArray insertObject:cmt atIndex:0];
                        }
                    }
                }
                
                id  comment_js =[resultt objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]])
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
                }
                
                id score =[resultt objectForKey:@"score"];
                if (score && [score isKindOfClass:[NSDictionary class]]) {
                    NSString *scoreMsg =[score objectForKey:@"score_msg"];
                    [WTStatusBar setStatusText:scoreMsg timeout:3 animated:YES];
                }
                [wSelf.tbView reloadData];
            }
        } failure:^(NSError *error) {
            [[ZToastManager ShardInstance] showtoast:@"回复失败"];
        }];
      
    }else{
        [self postComment:textViewGet.text];
    }

}

//
-(void)backBtnClick
{
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView=nil;
    [self.dataArray removeAllObjects];
    self.dataArray=nil;
    [[HcCustomKeyboard customKeyboard] textViewShowView:nil customKeyboardDelegate:nil];
    [HcCustomKeyboard customKeyboard].mDelegate=nil;
    [[HcCustomKeyboard customKeyboard].mTextView resignFirstResponder];
    [[HcCustomKeyboard customKeyboard].mTextView removeFromSuperview];
    [HcCustomKeyboard customKeyboard].mTextView=nil;
    self.keyBordView=nil;
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)postComment:(NSString*)txt
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:@"comment" forKey:@"action"];
    [dict setValue:@"" forKey:@"comment_id"];
    [dict setValue:self.commentId forKey:@"photo_id"];
    [dict setValue:@"" forKey:@"good_id"];
   
    [dict setValue:txt forKey:@"text"];
    
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    wSelf.isRequesting = YES;
    [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
        [wSelf commentResultObject:result];
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] showtoast:@"点评失败"];
        //     [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
    
}

-(void)commentResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        {
            [[ZToastManager ShardInstance] showtoast:[resultObject objectForKey:@"msg"]];
            id comments =[resultObject objectForKey:@"comments"];
            if (comments && [comments isKindOfClass:[NSArray class]]) {
                for (id cmt in comments) {
                    if (cmt && [cmt isKindOfClass:[NSDictionary class]]) {
                        [_dataArray insertObject:cmt atIndex:0];
                    }
                }
            }
            
            id  comment_js =[resultObject objectForKey:@"comment_js"];
            if (comment_js && [comment_js isKindOfClass:[NSString class]])
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
            }
            
            id score =[resultObject objectForKey:@"score"];
            if (score && [score isKindOfClass:[NSDictionary class]]) {
                NSString *scoreMsg =[score objectForKey:@"score_msg"];
                [WTStatusBar setStatusText:scoreMsg timeout:3 animated:YES];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentList" object:nil];
    }
    
    [_tbView reloadData];
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_sunUser:
        {
            if (obj && [obj isKindOfClass:[NSDictionary class]])
            {
                NSString *userid =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"user_id"]] replaceNullString];
                NSString *largeFace =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"largeFace"]] replaceNullString];
                NSString *nick_name =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"nick_name"]] replaceNullString];
                
                OtherUserCenterVC *user =[[OtherUserCenterVC alloc] init];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:[NSString stringWithFormat:@"%@",largeFace] forKey:@"largeFace"];
                [dict setValue:[NSString stringWithFormat:@"%@",userid] forKey:@"user_id"];
                [dict setValue:[NSString stringWithFormat:@"%@",nick_name] forKey:@"nick_name"];
                user.userDictionary=dict;
                [self.navigationController pushViewController:user animated:YES];
                return;
            }
        }
            break;
        case BEventType_ding:
        {
            NSString *cmid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"comment_id"]];
            int had_top=[[obj objectForKey:@"had_top"] intValue];
            if(had_top)
            {
                [[ZToastManager ShardInstance] showtoast:@"已顶"];
                return;
            }
            if ([self isLogin]) {
                [self postTop:cmid type:1];
            }
            
        }
            break;
        case BEventType_cai:
        {
            NSString *cmid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"comment_id"]];
            int had_bottom=[[obj objectForKey:@"had_bottom"] intValue];
            if(had_bottom)
            {
                [[ZToastManager ShardInstance] showtoast:@"已踩"];
                return;
            }
            if ([self isLogin]) {
                [self postTop:cmid type:2];
            }
        }
            break;
        case BEventType_comment:
        {
            if ([self isLogin]) {
                _commentDictionary = [NSMutableDictionary dictionaryWithDictionary:obj];
                UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                              initWithTitle:nil
                                              delegate:self
                                              cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                              otherButtonTitles:@"回复",@"@TA",nil];
                actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
                [actionSheet showInView:self.view];
            }
            
        }
            break;
        default:
            break;
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            if ([self isLogin]) {
                _commentType = 1;
                [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
            }
        }
            break;
        case 1:
        {
            if ([self isLogin]) {
                _commentType = 2;
                if (_commentDictionary && [_commentDictionary isKindOfClass:[NSDictionary class]]) {
                    NSString *username = [_commentDictionary objectForKey:@"nick_name"];
                    NSString *name =[NSString stringWithFormat:@"@%@ ", username];
                    [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
                    [HcCustomKeyboard customKeyboard].mTextView.text =name;
                }
            }
        }
            break;
     
        default:
            break;
    }
}
//顶踩
-(void)postTop:(NSString*)comment_id type:(int)type
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    if (type==1) {
        [dict setValue:@"push_top" forKey:@"action"];
    }else{
        [dict setValue:@"push_bottom" forKey:@"action"];
    }
    [dict setValue:comment_id forKey:@"comment_id"];
    [dict setValue:@"" forKey:@"photo_id"];
    [dict setValue:@"" forKey:@"text"];
    
    __weak typeof (self) wSelf = self;
    [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [[ZToastManager ShardInstance] showtoast:[result objectForKey:@"msg"]];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultt = (NSDictionary*)result;
            NSString *msg = [resultt stringForKey:@"msg"];
            if (msg.length>0) {
                [[ZToastManager ShardInstance] showtoast:msg];
            }
            
            id  comment_js =[resultt objectForKey:@"comment_js"];
            if (comment_js && [comment_js isKindOfClass:[NSString class]])
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
            }
        }
        
        
        [wSelf getCommentListData];
        [_tbView reloadData];
        
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] showtoast:@"顶踩失败"];
        //    [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
    
}
@end
